package filters

import (
	"github.com/sentiger/go-gateway/src"
	"log"
	"strconv"
	"strings"
)

type StripPrefixFilter struct{}

func init() {
	// 自动注册过滤器
	src.RegisterFilter("StripPrefix", NewStripPrefixFilter())
}

func NewStripPrefixFilter() *StripPrefixFilter {
	return &StripPrefixFilter{}
}

func (filter *StripPrefixFilter) Apply(config interface{}) src.GatewayFilter {
	return func(exchange *src.ServerWebExchange) src.ResponseFilter {
		defIndex := 1
		config := src.ValueConfig(config.(string))
		// 字符串转换为整
		i, err := strconv.Atoi(config.GetValue()[0])
		if err != nil {
			log.Println("转换错误", err)
		} else if i > defIndex {
			defIndex = i
		}
		pathList := strings.Split(exchange.Request.URL.Path, "/")
		// 这里防止StripPrefix=3 ，这里的值大于path长度
		if len(pathList) < defIndex {
			defIndex = len(pathList)
		}
		exchange.Request.URL.Path = strings.Join(pathList[defIndex:], "/")
		return nil
	}
}
func (filter *StripPrefixFilter) GetOrder() int {
	return 3
}
